package model.generator;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import model.Course;
import model.OfferedCourse;
import model.Registration;
import model.container.CourseContainer;
import model.container.RegistrationContainer;
import model.container.StudentContainer;
import util.Date;

public class RegistrationGenerator {
	
	// METHODS
	private static Random random = new Random();
	/** Generates a predefined number of registrations */
	public static Set<Registration> generateRegistrations(int count) throws Exception {
		
		// Initialize list
		Set<Registration> registrations = new HashSet<Registration>();
		// Fill list
		for(int i = 0; i < count; i++){
			Registration registration = new Registration();
			registration.setRegistrationDate(new Date("01/09/" + (2005 + random.nextInt(6))));
			// Add to list
			registrations.add(registration);
		}
		// Return list
		return registrations;
	}
	
	/**
	 * Initialize the registration reference fields
	 */
	public static void finishRegistrationInitialisation() {
		RegistrationContainer registrationContainer = RegistrationContainer.getInstance();
		StudentContainer studentContainer = StudentContainer.getInstance();
		CourseContainer courseContainer = CourseContainer.getInstance();
		Set<Registration> registrations = registrationContainer.getRegistrations();
		List<Course> courses = courseContainer.getCourses();
		//iterate over all the registrations and set their reference fields
		for(Registration registration: registrations){
			// set Student
			registration.setStudent(studentContainer.getStudents().get(random.nextInt(studentContainer.getStudentCount())));
			// get random offeredCourse
			OfferedCourse offeredCourse = null;
			Course course = courses.get(random.nextInt(courseContainer.getCourseCount()));
			if(course.getOfferedcourses().size() > 0){
				offeredCourse = course.getOfferedcourses().get(random.nextInt(course.getOfferedcourses().size()));
			}
			// set offered course
			registration.setOfferedCourse(offeredCourse);
						
		}
		
	}
	
	public static Set<Registration> getRandomRegistrations(){
		RegistrationContainer registrationContainer = RegistrationContainer.getInstance();
		int toIndex = random.nextInt(registrationContainer.getRegistrationCount());
		int fromIndex = toIndex > 0 ? random.nextInt(toIndex):0;
		Registration[] registrations = Arrays.copyOfRange(registrationContainer.getRegistrations().toArray(new Registration[0]), fromIndex, toIndex);
		return new HashSet<Registration>(Arrays.asList(registrations));
	}
}